//
//  YSGPersonInfoViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/11/18.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class YSGPersonInfoViewController: BaseViewController {
    
    private var dataSource: [YSGPersonInfoCellViewModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var name: String
    private var avatar: String
    
    init(name: String, avatar: String) {
        self.name = name
        self.avatar = avatar
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "我的信息"

        let dataSource = [
            YSGPersonInfoCellViewModel(name: "", avatar: avatar, cellType: .avatar),
            YSGPersonInfoCellViewModel(name: name, avatar: "", cellType: .name),
            YSGPersonInfoCellViewModel(name: "", avatar: "", cellType: .password),
            YSGPersonInfoCellViewModel(name: "", avatar: "", cellType: .address),
            YSGPersonInfoCellViewModel(name: "", avatar: "", cellType: .cancellation),
            YSGPersonInfoCellViewModel(name: "", avatar: "", cellType: .logout)
        ]
        self.dataSource = dataSource
    }


    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(YSGPersonInfoCell.nibForCell(),
                               forCellReuseIdentifier: YSGPersonInfoCell.reuseIdentifier())
            tableView.register(SettingLogoutCell.nibForCell(),
                               forCellReuseIdentifier: SettingLogoutCell.reuseIdentifier())
        }
    }

}

extension YSGPersonInfoViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let vm = dataSource[indexPath.section]
        switch vm.cellType {
        case .logout:
            let cell = tableView.dequeueReusableCell(withIdentifier: SettingLogoutCell.reuseIdentifier(),
                                                                for: indexPath) as! SettingLogoutCell
            cell.logoutBtn.addTarget(self, action: #selector(logout), for: .touchUpInside)
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGPersonInfoCell.reuseIdentifier(), for: indexPath) as! YSGPersonInfoCell
            cell.configure(with: dataSource[indexPath.section])
            return cell
        }
    }
}

extension YSGPersonInfoViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let vm = dataSource[indexPath.section]
        return vm.cellHeight
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let cell = tableView.cellForRow(at: indexPath) as? YSGPersonInfoCell else { return }
        
        let vm = dataSource[indexPath.section]
        switch vm.cellType {
        case .avatar:
            pushChangeAvatar(vm, imageView: cell.avatarView, indexPath: indexPath)
        case .name:
            pushSetupNameVc(at: indexPath)
        case .password:
            pushChangePsdVc()
        case .cancellation:
            pushModifyUserStatusVc()
        case .address:
            pushAddressVc()
        default:
            break
        }
    }
}

// MARK: - Helpers
private extension YSGPersonInfoViewController {
    /// 跳转修改头像
    func pushChangeAvatar(_ vm: YSGPersonInfoCellViewModel, imageView: UIImageView, indexPath: IndexPath) {
        let imagePicker = YSGImagePicker(currentImageView: imageView, isWebImage: true)
        let imagePickerNav = BaseNavigationController(rootViewController: imagePicker)
        imagePickerNav.modalPresentationStyle = .custom
        present(imagePickerNav, animated: true, completion: nil)
        
        imagePicker.handleClosure = { [weak self] in
            guard let self = self else { return }
            var vm = self.dataSource[indexPath.section]
            vm.avatar = UserDefaults.userAvatar
            self.dataSource[indexPath.section] = vm
            self.tableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }
    
    /// 跳转设置姓名
    func pushSetupNameVc(at indexPath: IndexPath) {
        let setupNameVc = YSGSetupNameViewController(name: name)
        let setupNameNav = BaseNavigationController(rootViewController: setupNameVc)
        setupNameNav.modalPresentationStyle = .custom
        present(setupNameNav, animated: true, completion: nil)
        
        setupNameVc.handleClosure = { [weak self] name in
            guard let self = self else { return }
            self.name = name
            var vm = self.dataSource[indexPath.section]
            vm.name = name
            self.dataSource[indexPath.section] = vm
            self.tableView.reloadRows(at: [indexPath], with: .automatic)
            
            UserDefaults.saveUsername(name)
        }
    }
    
    /// 跳转收货地址
    func pushAddressVc() {
        let addressVc = FamilyAddressController()
        addressVc.fromProfile = true
        navigationController?.pushViewController(addressVc, animated: true)
    }
    
    
    /// 跳转收货地址
    func pushModifyUserStatusVc() {
        YSGWrongAlertViewController.show(title: "是否注销账号", describe: "注销账号后无法登录，如需恢复需要管理员处理，请谨慎注销", needTextConfirm: "注销账号", viewController: self) {
            HttpTool.shared.request(api: ApiManager.modifyUserStatus, model: Bool.self) { result in
                switch result {
                case .success(_):
                    HUDTool.show(message: "账号注销成功，正在退出")
                    ProfileViewModel.logout { (code, errorMsg) in
                        HUDTool.hideActivity()
                        switch code {
                        case .success:
                            WebSocketManager.destroy()
                            UserDefaults.removeUserInfo()
                            (mainWindow.rootViewController as? MainViewController)?.selectedIndex = 0
                            self.navigationController?.popToRootViewController(animated: true)
                        case .failure:
                            HUDTool.showError(message: errorMsg)
                        }
                    }
                case .failure(let error):
                    error.showToast()
                }
            }
        }
    }
    
    /// 跳转修改密码
    func pushChangePsdVc() {
        let changePsdVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "changePwdVcId") as! ChangePwdViewController
        navigationController?.pushViewController(changePsdVc, animated: true)
    }
    
    /// 退出登录
    @objc func logout() {
        let alert = UIAlertController(title: "正在退出登录,确认要退出登录吗?", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "退出登录", style: .default, handler: { _ in
            WebSocketManager.destroy()
            UserDefaults.removeUserInfo()
            (mainWindow.rootViewController as? MainViewController)?.selectedIndex = 0
            self.navigationController?.popToRootViewController(animated: true)
            AppDelegate.logout(inSelf: true)
        }))
        alert.addAction(UIAlertAction(title: "留下来再看看", style: .cancel, handler: nil))
        showDetailViewController(alert, sender: nil)
    }
}
